import cv2
import numpy as np
from deepface import DeepFace
import time
import matplotlib.pyplot as plt


def show_emotion_distribution(emotions):
    """显示情绪分布弹窗"""
    plt.figure(figsize=(10, 6))
    colors = ['#FF6347', '#20B2AA', '#9370DB', '#32CD32', '#FFD700', '#FF69B4', '#1E90FF']
    bars = plt.bar(emotions.keys(), emotions.values(), color=colors)

    plt.title('Emotion Probability Distribution', fontsize=14)
    plt.xlabel('Emotions', fontsize=12)
    plt.ylabel('Probability (%)', fontsize=12)
    plt.ylim(0, 100)
    plt.xticks(rotation=45, ha='right')

    # 添加数值标签
    for bar in bars:
        height = bar.get_height()
        plt.text(bar.get_x() + bar.get_width() / 2., height,
                 f'{height:.2f}%',
                 ha='center', va='bottom')
    plt.tight_layout()
    plt.show()


if __name__ == '__main__':
    start_time = time.time()
    img_path = "test01.png"

    # 分析图片
    analysis_start = time.time()
    objs = DeepFace.analyze(
        img_path=img_path,
        actions=['emotion'],
        detector_backend='opencv',
        enforce_detection=False
    )
    analysis_time = time.time() - analysis_start

    # 处理图像
    img = cv2.imread(img_path)
    img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # 人脸标注
    for face in objs:
        region = face['region']
        x, y, w, h = region['x'], region['y'], region['w'], region['h']
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
        cv2.putText(img, face['dominant_emotion'],
                    (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)

    # 创建对比图窗口
    fig = plt.figure(figsize=(15, 7))

    # 显示标注后的原图
    ax1 = fig.add_subplot(1, 2, 1)
    ax1.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))  # 转换颜色通道
    ax1.set_title('Detected Face')
    ax1.axis('off')

    # 显示情绪分布
    ax2 = fig.add_subplot(1, 2, 2)
    emotions = {k: float(v) for k, v in objs[0]['emotion'].items()}
    colors = ['#FF6347', '#20B2AA', '#9370DB', '#32CD32', '#FFD700', '#FF69B4', '#1E90FF']
    bars = ax2.bar(emotions.keys(), emotions.values(), color=colors)

    ax2.set_title('Emotion Distribution')
    ax2.set_ylim(0, 100)
    plt.xticks(rotation=45, ha='right')

    # 添加柱状图数值
    for bar in bars:
        height = bar.get_height()
        ax2.text(bar.get_x() + bar.get_width() / 2., height,
                 f'{height:.2f}%',
                 ha='center', va='bottom')

    plt.tight_layout()

    # 控制台输出
    total_time = time.time() - start_time
    print("\n" + "=" * 50)
    print("详细情绪分析结果：")
    for emotion, value in emotions.items():
        print(f"{emotion.upper():<10}: {value:.4f}%")
    print("\n" + "-" * 50)
    print(f"人脸分析耗时: {analysis_time:.2f}s")
    print(f"总运行时间: {total_time:.2f}s")
    print("=" * 50)

    # 显示所有弹窗
    plt.show()

    # 单独显示OpenCV窗口（可选）
    cv2.imshow('Face Detection', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()